<?php

namespace App\Http\Controllers;

use App\Assignment;
use App\AssignmentCompletion;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class AssignmentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $date = $request->input('date', date('Y-m-d'));
        $query = Assignment::with(['completions' => function($query) {
            $query->where('student_id', Auth::id());
        }])->whereNull('deleted_at');

        // 获取选中日期的开始和结束时间
        $startOfDay = Carbon::parse($date)->startOfDay();
        $endOfDay = Carbon::parse($date)->endOfDay();
        $startOfWeek = Carbon::parse($date)->startOfWeek();
        $endOfWeek = Carbon::parse($date)->endOfWeek();

        // 构建查询条件
        $query->where(function($q) use ($startOfDay, $endOfDay, $startOfWeek, $endOfWeek) {
            // 当日作业
            $q->where(function($q) use ($startOfDay, $endOfDay) {
                $q->where('type', 'daily')
                  ->whereBetween('due_date', [$startOfDay, $endOfDay]);
            })
            // 当日打卡
            ->orWhere(function($q) use ($startOfDay, $endOfDay) {
                $q->where('type', 'checkin')
                  ->whereBetween('due_date', [$startOfDay, $endOfDay]);
            })
            // 当前周作业
            ->orWhere(function($q) use ($startOfWeek, $endOfWeek) {
                $q->where('type', 'weekly')
                  ->whereBetween('due_date', [$startOfWeek, $endOfWeek]);
            });
        });

        // 获取作业列表并按完成状态和截止日期排序
        $assignments = $query->get()->sortBy(function($assignment) {
            // 获取当前用户的完成状态
            $isCompleted = $assignment->completions->isNotEmpty() && 
                          $assignment->completions->first()->is_completed;
            
            // 使用完成状态作为主要排序依据，截止日期作为次要排序依据
            return [
                $isCompleted ? 1 : 0, // 未完成的排在前面
                $assignment->due_date
            ];
        })->values();

        return view('assignments.index', compact('assignments', 'date'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('assignments.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'content' => 'required|string',
            'source' => 'required|in:school,institution',
            'subject' => 'required|in:chinese,math,english,science',
            'type' => 'required|in:daily,weekly,checkin',
            'due_date' => 'required|date',
        ]);

        // 生成标题
        $sourceText = $validated['source'] === 'school' ? '学校' : '机构';
        $subjectText = [
            'chinese' => '语文',
            'math' => '数学',
            'english' => '英语',
            'science' => '科学'
        ][$validated['subject']];
        $title = $sourceText . $subjectText . '作业';

        // 如果是打卡任务，需要为截止日期前的每一天创建任务
        if ($validated['type'] === 'checkin') {
            $startDate = Carbon::now()->startOfDay();
            $endDate = Carbon::parse($validated['due_date'])->endOfDay();
            
            // 使用事务确保数据一致性
            \DB::transaction(function() use ($validated, $title, $startDate, $endDate) {
                while ($startDate <= $endDate) {
                    Assignment::create([
                        'title' => $title,
                        'content' => $validated['content'],
                        'source' => $validated['source'],
                        'subject' => $validated['subject'],
                        'type' => 'checkin',
                        'due_date' => $startDate->format('Y-m-d'),
                        'created_by' => Auth::id(),
                    ]);
                    
                    $startDate->addDay();
                }
            });
        } else {
            // 其他类型的作业直接创建
            Assignment::create(array_merge($validated, [
                'title' => $title,
                'created_by' => Auth::id(),
            ]));
        }

        return redirect()->route('assignments.index')
            ->with('success', '作业创建成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Assignment $assignment)
    {
        return view('assignments.show', compact('assignment'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Assignment $assignment)
    {
        return view('assignments.edit', compact('assignment'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Assignment $assignment)
    {
        $validated = $request->validate([
            'content' => 'required|string',
            'source' => 'required|in:school,institution',
            'subject' => 'required|in:chinese,math,english,science',
            'type' => 'required|in:daily,weekly,checkin',
            'due_date' => 'required|date'
        ]);

        // 检查是否是自己的作业
        if ($assignment->created_by !== Auth::id()) {
            return redirect()->back()
                ->with('error', '您只能编辑自己创建的作业');
        }

        // 生成标题
        $sourceText = $validated['source'] === 'school' ? '学校' : '机构';
        $subjectText = [
            'chinese' => '语文',
            'math' => '数学',
            'english' => '英语',
            'science' => '科学'
        ][$validated['subject']];
        $title = $sourceText . $subjectText . '作业';

        $assignment->update(array_merge($validated, [
            'title' => $title
        ]));

        return redirect()->route('assignments.index')
            ->with('success', '作业更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Assignment $assignment)
    {
        // 检查是否是自己的作业
        if ($assignment->created_by !== Auth::id()) {
            return redirect()->back()
                ->with('error', '您只能删除自己创建的作业');
        }

        // 使用软删除
        $assignment->delete();

        return redirect()->route('assignments.index')
            ->with('success', '作业已删除');
    }

    public function complete(Assignment $assignment)
    {
        $completion = AssignmentCompletion::updateOrCreate(
            [
                'assignment_id' => $assignment->id,
                'student_id' => Auth::id(),
            ],
            [
                'is_completed' => true,
                'completed_at' => now(),
            ]
        );

        return redirect()->back()
            ->with('success', '作业完成状态已更新');
    }
}
